<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
class User_lost_model extends CI_Model {
	public function __construct() {
            parent::__construct();
            $this->load->database();
	}
	
        public function new_request($email, $originseed) {  //提交一个新的找回密码的请求
            $query = $this->db->get_where('user', array('email' => $email));
            if ($query->num_rows() > 0) {
                $row = $query->row_array();
                $newrequest  = array (
                    "user_id" => $row['user_id'],
                    "verifycode" => md5(md5($originseed)),
                    "is_used" => FALSE
                );
                if( $this->verify_originseedhash(md5($originseed)) )
                    return FALSE;
                else {
                    $this->db->insert('user_lostrequest', $newrequest);
                    return TRUE;
                }
            }
            else return FALSE;
        }
        
        public function verify_originseedhash($originseedhash) {    //验证一个请求中给出的验证是否真实
            $query = $this->db->get_where('user_lostrequest', array('verifycode' => md5($originseedhash)));
            if ($query->num_rows() > 0) {
                foreach ($query->result() as $row)
                {
                   if (!($row->is_used))
                       return TRUE;
                }
                return FALSE;
            }
            else
                return FALSE;
        }
        
        public function change_pwd_by_originseedhash($originseedhash, $pwd, $salt) {    //根据验证码找出对应的用户，修改密码
            $query = $this->db->get_where('user_lostrequest', array('verifycode' => md5($originseedhash), 'is_used' => FALSE));
            if ($query->num_rows() > 0) {
                $row = $query->row_array();
                $query2 = $this->db->get_where('user', array('user_id' => $row['user_id']));
                if ($query2->num_rows() > 0) {
                    $this->db->update('user', array('password' => $pwd, 'salt' => $salt), array('user_id' => $row['user_id']));
                    $this->db->update('user_lostrequest', array('is_used' => TRUE), array('request_id' => $row['request_id']));
                    return TRUE;
                }
                else return FALSE;
            }
            else return FALSE;
        }        
}
?>
